package com.xp.agent.task;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;

import com.xp.agent.common.CommonProperties;
import com.xp.agent.common.Item;
import com.xp.agent.dto.ConfigDto;

public class ConfigLoader implements Runnable {

	private long lastModifyTime;
	private File configFile;

	public ConfigLoader(String configFilePath) {
		super();
		this.configFile = new File(configFilePath);
		if (!configFile.exists()) {
			configFile = null;
		}
	}

	@Override
	public void run() {
		try {
			reloadFile();
			Thread.sleep(CommonProperties.RELOAD_TIME);
		} catch (Throwable t) {
			// catching all exception for go on
		}
	}

	private void reloadFile() throws Exception {
		if (configFile == null) {
			return;
		}
		/*
		 * checking file,load file when it changes
		 */
		if (lastModifyTime != configFile.lastModified()) {
			loadFile();
		}
	}

	public void loadFile() throws Exception {
		if (configFile == null) {
			return;
		}
		lastModifyTime = configFile.lastModified();
		try (InputStream in = new FileInputStream(configFile);) {
			Properties pro = new Properties();
			pro.load(in);

			String property = pro.getProperty(CommonProperties.LOG_FILE_PRO);
			if (property != null) {
				CommonProperties.logPath.set(property.trim());
			} else {
				// no set,use current path
				CommonProperties.logPath.set(".");
			}

			for (Item item : Item.values()) {
				try {
					Long itemValue = Long.valueOf(pro.getProperty(item.getItemName()).trim());
					ConfigDto.instance.setPro(item.getItemName(), itemValue);
				} catch (Throwable t) {
				}
			}
		}
	}
}
